package com.google.android.apps.wakemewhere.ui;

import com.google.android.apps.wakemewhere.Alarm;
import com.google.android.apps.wakemewhere.Alarms;
import com.google.android.apps.wakemewhere.IntentExtras;
import com.google.android.apps.wakemewhere.ProximityAlertAlarmArbiter;
import com.google.android.apps.wakemewhere.R;

import android.content.ContentValues;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.preference.CheckBoxPreference;
import android.preference.EditTextPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;

public class SetAlarmActivity extends PreferenceActivity implements Preference.OnPreferenceChangeListener {
	private CheckBoxPreference enabledPreference;
	private CheckBoxPreference vibratePreference;
	private EditTextPreference labelPreference;
	private LocationPreference locationPreference;

	private long alarmId = -1;
	private long latitudeE6;
	private long longitudeE6;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.set);
		addPreferencesFromResource(R.xml.alarm_prefs);
        
		Intent intent = getIntent();
		alarmId = intent.getLongExtra(IntentExtras.ALARM_ID, -1);
		
		Alarm alarm = null;
		if (alarmId != -1) {
			alarm = Alarms.getAlarm(getContentResolver(), alarmId);
		} else {
			alarm = new Alarm();
		}
		
		enabledPreference = (CheckBoxPreference) findPreference("enabled");
		vibratePreference = (CheckBoxPreference) findPreference("vibrate");
        locationPreference = (LocationPreference) findPreference("location");
		labelPreference = (EditTextPreference) findPreference("label");
		
		locationPreference.setActivity(this);
		
		// Allow fields in the alarm to be overridden by incoming intent data
		if (intent.hasExtra(IntentExtras.LATITUDE) && intent.hasExtra(IntentExtras.LONGITUDE)) {
			latitudeE6 = intent.getLongExtra(IntentExtras.LATITUDE, 0);
			longitudeE6 = intent.getLongExtra(IntentExtras.LONGITUDE, 0);
			alarm.setLocation(latitudeE6, longitudeE6);
		} else {
			latitudeE6 = alarm.getLatitudeE6();
			longitudeE6 = alarm.getLongitudeE6();
		}
		
		updatePreferences(alarm);
		
		enabledPreference.setOnPreferenceChangeListener(this);
		vibratePreference.setOnPreferenceChangeListener(this);
		locationPreference.setOnPreferenceChangeListener(this);
		labelPreference.setOnPreferenceChangeListener(this);
		{
			View doneButton = findViewById(R.id.alarm_save);
			doneButton.setOnClickListener(new DoneButtonClicked());
		}

		{
			View deleteButton = findViewById(R.id.alarm_delete);
			deleteButton.setOnClickListener(new DeleteButtonClicked());
		}
	}
	
	@Override
	public void onBackPressed() {
		save();
		super.onBackPressed();
	}
	
	private void openAlarmListActivity() {
		Intent intent = new Intent(SetAlarmActivity.this, AlarmListActivity.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
		startActivity(intent);		 
	}
	
	private class DoneButtonClicked implements OnClickListener {
		public void onClick(View v) {
			save();
			openAlarmListActivity();
		}
	}
	
	private class DeleteButtonClicked implements OnClickListener {
		public void onClick(View v) {
			delete();
			openAlarmListActivity();
		}
	}
	
	private void delete() {
		if (alarmId == -1) {
			toast("Alarm not saved");
		} else {
			getContentResolver().delete(Alarms.uriForId(alarmId), null, null);
			toast("Alarm deleted");
		}
	}
	
	private void save() {
		if (locationPreference == null || 
			labelPreference == null || 
			enabledPreference == null ||
			vibratePreference == null) {
			return;
		}
		
		Alarm alarm = new Alarm();
		alarm.setLocation(latitudeE6, longitudeE6);
		alarm.setLabel(labelPreference.getText());
		alarm.setEnabled(enabledPreference.isChecked());
		alarm.setVibrate(vibratePreference.isChecked());
		ContentValues values = new ContentValues();
		alarm.writeOnto(values);
		
		if (alarmId == -1) {
			getContentResolver().insert(Alarms.CONTENT_URI, values);
			toast("Alarm created");
		} else {
			getContentResolver().update(Alarms.uriForId(alarmId), values, null, null);
			toast("Alarm updated");
		}
	}
	
	private void toast(String message) {
		Toast.makeText(SetAlarmActivity.this.getBaseContext(), 
				message, Toast.LENGTH_SHORT).show();
	}
	
	private static final Handler sHandler = new Handler();

	public boolean onPreferenceChange(final Preference preference, Object newValue) {
		sHandler.post(new Runnable() {
            public void run() {
                if (preference != enabledPreference) {
                    enabledPreference.setChecked(true);
                }
             
                if (preference == labelPreference) {
                	String label = labelPreference.getText();
                	labelPreference.setSummary(label);
                }
            }
        });
        return true;
    }
	
	private void updatePreferences(Alarm alarm) {
		enabledPreference.setChecked(alarm.isEnabled());
		vibratePreference.setChecked(alarm.shouldVibrate());
		labelPreference.setText(alarm.getLabel());
		labelPreference.setSummary(alarm.getLabel());
		longitudeE6 = alarm.getLongitudeE6();
		latitudeE6 = alarm.getLatitudeE6();
		locationPreference.setSummary(Alarm.locationSummaryString(latitudeE6, longitudeE6));
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (data.hasExtra(IntentExtras.LATITUDE) && data.hasExtra(IntentExtras.LONGITUDE)) {
			latitudeE6 = data.getLongExtra(IntentExtras.LATITUDE, 0);
			longitudeE6 = data.getLongExtra(IntentExtras.LONGITUDE, 0);
		}
		locationPreference.setSummary(Alarm.locationSummaryString(latitudeE6, longitudeE6));
	}
}

